package com.hbisoft.pickitexample.slice;

import com.hbisoft.pickit.PickiT;
import com.hbisoft.pickit.PickiTCallbacks;
import com.hbisoft.pickit.ResourceTable;
import com.hbisoft.pickitexample.utils.PermissionBridge;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

public class MainAbilitySlice extends AbilitySlice implements PickiTCallbacks,
        PermissionBridge.OnPermissionStateListener {

    private static final int SELECT_VIDEO_REQUEST = 777;
    public static final int PERMISSION_REQ_CODE = 23;
    private static final int RESULT_OK = -1;
    private static final String[] REQUEST_PERMISSIONS = new String[]{
            SystemPermission.READ_USER_STORAGE
    };
    private Text pickItText;
    private Text originalTitle;
    private Text originalText;
    private Text pickItTitle;
    private Button textPickFile;
    private PickiT pickiT;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        textPickFile = (Button) findComponentById(ResourceTable.Id_text_pick);
        originalTitle = (Text) findComponentById(ResourceTable.Id_originalTitle);
        originalText = (Text) findComponentById(ResourceTable.Id_originalTv);
        pickItTitle = (Text) findComponentById(ResourceTable.Id_pickitTitle);
        pickItText = (Text) findComponentById(ResourceTable.Id_pickitTv);
        initClick();
        pickiT = new PickiT(this, this, this);
        new PermissionBridge().setOnPermissionStateListener(this);
    }

    /**
     * Toast show
     *
     * @param msg
     */
    private void showLongToast(String msg) {
        ToastDialog toastDialog = new ToastDialog(getContext());
        toastDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toastDialog.setDuration(1000);
        toastDialog.setOffset(0, 100);
        toastDialog.setText(msg);
        Text toastText = (Text) toastDialog.getComponent();
        if (toastText != null) {
            toastText.setMultipleLine(true);
            toastText.setTextSize(14, Text.TextSizeType.FP);
            toastText.setTextColor(Color.BLACK);
            toastText.setPaddingBottom(20);
            toastText.setPaddingTop(20);
            toastText.setMarginLeft(20);
            toastText.setMarginRight(20);
            ShapeElement toastBackground = new ShapeElement();
            toastBackground.setRgbColor(new RgbColor(245, 245, 245));
            toastBackground.setCornerRadius(20f);
            toastText.setBackground(toastBackground);
        }
        toastDialog.show();
    }

    private void initClick() {
        textPickFile.setClickedListener(component -> {
            if (checkSelfPermission()) {
                openGallery();
            }
            originalText.setVisibility(Component.INVISIBLE);
            originalTitle.setVisibility(Component.INVISIBLE);
            pickItTitle.setVisibility(Component.INVISIBLE);
            pickItText.setVisibility(Component.INVISIBLE);
        });
    }

    private void openGallery() {
        Intent intent = new Intent();
//        intent.setType("video/*");
        intent.setType("image/*");
        intent.setAction("android.intent.action.PICK");
        intent.setAction("android.intent.action.GET_CONTENT");
        intent.setParam("return-data", true);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.addFlags(0x00000001);
        startAbilityForResult(intent, SELECT_VIDEO_REQUEST);
    }

    /**
     * Check if permission was granted
     *
     * @return boolean
     */
    private boolean checkSelfPermission() {
        if (verifySelfPermission(REQUEST_PERMISSIONS[0]) != IBundleManager.PERMISSION_GRANTED) {
            requestPermissionsFromUser(REQUEST_PERMISSIONS, PERMISSION_REQ_CODE);
            return false;
        }
        return true;
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == SELECT_VIDEO_REQUEST) {
            if (resultCode == RESULT_OK && resultData.getUri() != null) {
                pickiT.getPath(resultData.getUri());
                originalText.setText(String.valueOf(resultData.getUri()));
            }
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private ProgressBar mProgressBar;
    private Text percentText;
    private CommonDialog mDialog;

    @Override
    public void pickiTonUriReturned() {

    }

    @Override
    public void pickiTonStartListener() {
        mDialog = new CommonDialog(this);
        Component component = LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_dialog_layout, null, true);
        percentText = (Text) findComponentById(ResourceTable.Id_percentText);
        mProgressBar = (ProgressBar) findComponentById(ResourceTable.Id_mProgressBar);
        percentText.setClickedListener(component1 -> {
            pickiT.cancelTask();
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.remove();
            }
        });
        mDialog.setContentCustomComponent(component);
        mDialog.setSize(250, 350);
        mProgressBar.setMaxValue(100);
        mDialog.show();
    }

    @Override
    public void pickiTonProgressUpdate(int progress) {
        String progressPlusPercent = progress + "%";
        percentText.setText(progressPlusPercent);
        mProgressBar.setProgressValue(progress);
    }

    @Override
    public void pickiTonCompleteListener(String path, boolean wasDriveFile,
                                         boolean wasUnknownProvider, boolean wasSuccessful, String reason) {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.remove();
        }
        //  Check if it was a Drive/local/unknown provider file and display a Toast
        if (wasDriveFile) {
            showLongToast("Drive file was selected");
        } else if (wasUnknownProvider) {
            showLongToast("File was selected from unknown provider");
        } else {
            showLongToast("Local file was selected");
        }
        if (wasSuccessful) {
            pickItText.setText(path);
            originalTitle.setVisibility(Component.VISIBLE);
            originalText.setVisibility(Component.VISIBLE);
            pickItTitle.setVisibility(Component.VISIBLE);
            pickItText.setVisibility(Component.VISIBLE);
        } else {
            showLongToast("Error, Please see the log");
            pickItText.setVisibility(Component.VISIBLE);
            pickItText.setText(reason);
        }
    }

    @Override
    protected void onBackPressed() {
        pickiT.deleteTemporaryFile(this);
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isUpdatingConfigurations()) {
            pickiT.deleteTemporaryFile(this);
        }
    }

    @Override
    public void onPermissionGranted() {
        openGallery();
    }

    @Override
    public void onPermissionDenied() {
        showLongToast("No permission for " + SystemPermission.READ_USER_STORAGE);
    }
}
